package com.ssm.sport.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionTimeoutFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        // 检查是否是AJAX请求
        boolean isAjax = "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With"));
        
        // 如果会话不存在或已过期
        if (session == null) {
            if (isAjax) {
                // 对于AJAX请求，返回401状态码
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            } else {
                // 对于普通请求，重定向到登录页面
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/user/login");
                return;
            }
        }

        // 继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁方法
    }
} 